package com.zhongyewx.teachercert;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.meituan.android.walle.WalleChannelReader;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.tinker.entry.DefaultApplicationLike;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.PlatformConfig;
import com.zhongyewx.teachercert.db.ZYTCDataBase;
import com.zhongyewx.teachercert.utils.ZYSharedPreferencesUtils;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.mezu.MeizuRegister;
import org.android.agoo.xiaomi.MiPushRegistar;

import java.util.ArrayList;
import java.util.Iterator;

public class ZYApplication extends DefaultApplicationLike {

    private static ZYApplication instance;
    private static RefWatcher mRefWatcher;
    private ArrayList<Activity> mList = new ArrayList<Activity>();
    private static Application application;
    private static int tinkerFlags;
    private static boolean tinkerLoadVerifyFlag;
    private static long applicationStartElapsedTime;
    private static long applicationStartMillisTime;
    private static Intent tinkerResultIntent;

    public ZYApplication(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
        this.application = application;
        ZYApplication.tinkerFlags = tinkerFlags;
        ZYApplication.tinkerLoadVerifyFlag = tinkerLoadVerifyFlag;
        ZYApplication.applicationStartElapsedTime = applicationStartElapsedTime;
        ZYApplication.applicationStartMillisTime = applicationStartMillisTime;
        ZYApplication.tinkerResultIntent = tinkerResultIntent;
    }

    static {
        PlatformConfig.setWeixin("wx93c68d76c7f56a9e", "6df0a103d333ae58190fa621182c1450");
        PlatformConfig.setQQZone("101679112", "3d69275469cc46e2dab992f4438f737b");
    }

    public synchronized static ZYApplication getInstance() {
        if (null == instance) {
            instance = new ZYApplication(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime,
                    applicationStartMillisTime, tinkerResultIntent);
        }
        return instance;
    }
    @Override
    public void onCreate() {
        super.onCreate();

        Context mContext = getApplication().getApplicationContext();

        String channel = "";
        try {
            channel = WalleChannelReader.getChannel(mContext, "zyDefault");
        } catch (Exception e) {
            channel = "zyDefault";
        }

        /**
         * 注意: 即使您已经在AndroidManifest.xml中配置过appkey和channel值，也需要在App代码中调
         * 用初始化接口（如需要使用AndroidManifest.xml中配置好的appkey和channel值，
         * UMConfigure.init调用中appkey和channel参数请置为null）。
         */
        UMConfigure.init(mContext, "5d1318624ca35734eb00077f", channel, UMConfigure.DEVICE_TYPE_PHONE, "8257d970b0e150db1d45477bf48e01f2");
        // 选用MANUAL页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL);
        UMConfigure.setLogEnabled(true);//发布时设置为false

        //初始化推送
        initPuth(mContext);

        // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备
        Bugly.setIsDevelopmentDevice(mContext, false);
        // 多渠道需求
        // String channel = WalleChannelReader.getChannel(getApplication());
         Bugly.setAppChannel(mContext, channel);

        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId
        // 调试时，将第三个参数改为true
        Bugly.init(mContext, "900029763", false);
        mRefWatcher = setRefWatcher();
        initARouter();
        ZYSharedPreferencesUtils.initPreferences(mContext);

        ZYTCDataBase.instance(mContext);
    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

    private RefWatcher setRefWatcher(){
        if (LeakCanary.isInAnalyzerProcess(getApplication())) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(getApplication());
    }

    public static RefWatcher getRefWatcher() {
        return mRefWatcher;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ARouter.getInstance().destroy();
    }

    private void initARouter() {
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(application); // 尽可能早，推荐在Application中初始化
    }

    private void initPuth(Context mContext){

        //小米
        MiPushRegistar.register(mContext,"2882303761518036127", "5741803691127");
        //华为
        HuaWeiRegister.register((Application) mContext);
        //魅族
        MeizuRegister.register(mContext, "119573", "fcb2a5855e63459c821c441d518e03a2");
        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(mContext);
//注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
//              Log.i(TAG,"注册成功：deviceToken：-------->  " + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
//                Log.e("","注册失败：-------->  " + "s:" + s + ",s1:" + s1);
            }
        });
    }


    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public void removeActivity(Activity activity) {
        if (mList.size() > 1) {
            try {
                synchronized (mList) {
                    Iterator<?> iter = mList.iterator();
                    while (iter.hasNext()) {
                        Activity mActivity = (Activity) iter.next();
                        if (mActivity == activity) {
                            iter.remove();
                            mList.remove(activity);
                        }
                    }
                }
            } catch (Exception ex) {
            }
        } else if (mList.size() == 1){
            mList.remove(activity);
        }
    }

    // 遍历所有Activity并finish
    public void logOut() {
        try {

            synchronized (mList) {
                for (Iterator<?> it = mList.iterator(); it.hasNext(); ) {
                    Activity mActivity = (Activity) it.next();
                    if (mActivity != null && !mActivity.isFinishing()) {
                        mActivity.finish();
                    }
                }
            }
        } catch (Exception ex) {
        }
    }
}
